// 创建readline对象，监听控制台输入
const readline = require('../../common/inputListener');

// 获取配置文件中的模式
const {mode} = require('../../common/getConf');

// 获取版本文件
const versionFile = require('../../common/getVersionFile');

// 三和一个问题
const sQuestions = require('./sQuestions');

// p系列问题
const pQuestions = require('./pQuestions');

const eventEmitter = require('../../common/eventbus');

const { S_SERIES} = require('../../common/constans');

let content = versionFile(mode);

let rl = readline.init();

let stepQuestions;

console.log('当前打包模式是：' + mode);

if (mode === S_SERIES) {

  stepQuestions = sQuestions;

} else {

  stepQuestions = pQuestions;

}

let step = 0;

let start=function(currStep = 0) {

  step = currStep;

  if (stepQuestions.length == step) {
    
    rl.close();

    eventEmitter.emit('questions.done', { questions: stepQuestions, mode, config: content });
    
    return;

  }

  let questionInfo = stepQuestions[step];

  rl.question(questionInfo.question + ':', answer => {

    if (!questionInfo.skip && !answer) {

      console.log(questionInfo.question + ' 退出quit 或 ctrl+c')

    } else {

      if (questionInfo.callback instanceof Function) {

        questionInfo.callback.call(stepQuestions,answer, questionInfo, start);

      } else {

        questionInfo.answer = answer;

        step++;

        start(step);

      }

    }

  });

}

module.exports = function () {

  rl.on('line', input => {

    if (input === 'quit') {

      console.log('bye');

      process.exit();

    } else {

      if (stepQuestions.length == step) {

        return;

      }

      let questionInfo = stepQuestions[step];

      if (questionInfo.callback instanceof Function) questionInfo.callback.call(stepQuestions,input, questionInfo,start);

    }

  });

  start(currStep = 0);
  
}

